package ee.maoinvest.frontend.controller.command.electricitymetercommands;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import ee.maoinvest.backend.model.data.ElectricityMeter;
import ee.maoinvest.backend.services.ElectricityMeterService;
import ee.maoinvest.backend.services.implementations.ElectricityMeterServiceImpl;
import ee.maoinvest.frontend.controller.command.Command;
import ee.maoinvest.frontend.controller.formstringdataconverters.electricitymeterforms.ReplaceOrDeleteOuterTerritoryElectricityMeterFormConverter;
import ee.maoinvest.frontend.controller.requestprocessors.ElectricityMeterFormsRequestProcessor;

public class GetAndFillReplaceOrDeleteOuterTerritoryElectricityMeterFormWithInitialDataCommand implements Command
{
	private int operationResult = 0;
	private final int OPERATION_SUCCESSFUL = 1;
	private final int OPERATION_UNSUCCESSFUL = 0;

	private final int ID_PARSE_ERROR_IDENTIFICATOR = -1;
	
	@Override
	public int executeCommand(HttpServletRequest request,
			HttpServletResponse response) 
	{
		ElectricityMeterFormsRequestProcessor electricityMeterFormsRequestProcessor = null;
		ReplaceOrDeleteOuterTerritoryElectricityMeterFormConverter replaceOrDeleteOuterTerritoryElectricityMeterFormConverter = null;
		ElectricityMeter outerTerritoryElectricityMeter = null;
		ElectricityMeterService electricityMeterService = null;
		
		electricityMeterFormsRequestProcessor = new ElectricityMeterFormsRequestProcessor();
		
		int outerTerritoryElectricityMeterIDToReplace = 
				electricityMeterFormsRequestProcessor.getOuterTerritoryElectricityMeterIDToReplaceOrDelete(request);
		
		if (outerTerritoryElectricityMeterIDToReplace != ID_PARSE_ERROR_IDENTIFICATOR)
		{
			electricityMeterService = new ElectricityMeterServiceImpl();
			outerTerritoryElectricityMeter = electricityMeterService.getElectricityMeterByID(outerTerritoryElectricityMeterIDToReplace);
		
			if (outerTerritoryElectricityMeter != null)
			{
				replaceOrDeleteOuterTerritoryElectricityMeterFormConverter = 
						new ReplaceOrDeleteOuterTerritoryElectricityMeterFormConverter();
				replaceOrDeleteOuterTerritoryElectricityMeterFormConverter.fillWithInitialData(outerTerritoryElectricityMeter);
				
				HttpSession session = request.getSession();
				session.setAttribute("outerTerritoryElectricityMeter", outerTerritoryElectricityMeter);
				request.setAttribute("replaceOrDeleteOuterTerritoryElectricityMeterFormConverter", 
						replaceOrDeleteOuterTerritoryElectricityMeterFormConverter);
				operationResult = OPERATION_SUCCESSFUL;
			}
		}
		else
		{
			operationResult = OPERATION_UNSUCCESSFUL;
		}

		return operationResult;
	}
}